<?php

namespace App\Http\Controllers\DepartmentManagement;


use App\Common\Response;
use App\Http\Controllers\CommonController;
use App\Http\Controllers\WeChat\WechatController;
use App\Models\Admin;
use App\Models\Files;
use App\Models\FirstType;
use App\Models\Operation;
use App\Models\Product;
use App\Models\Progress;
use App\Models\ProgressList;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redirect;
use \Illuminate\Contracts\Session\Session;
use Illuminate\Support\Facades\Storage;
use Mockery\Exception;
use Request;
use Symfony\Component\HttpFoundation\Request as Req;

class ProjectManagementController extends CommonController
{
    protected $admin_table = "admin";
    protected $pageNumber  = 15;

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 项目部登录界面
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function login()
    {
        return view( 'departmentManagement/project/login' );
    }

    public function loginOut()
    {

        $Session   = Session();
        $projecter = $Session->remove( 'projecter' );

        return redirect()->route( 'management.project.login' );
    }


    public function doLogin()
    {

        $request       = Request::all();
        $where_project = [ "type" => 3,"password" => md5( $request[ 'password' ] ),"account" => $request[ 'account' ],
        ];

        $projecter_model = Admin::where( $where_project )->first();


        if (!empty( $projecter_model )){
            $projecter    = $projecter_model->toArray();
            $Session      = Session();
            $session_data = [ "projecter_id" => $projecter[ 'id' ],"projecter_name" => "项目部-" . $projecter[ 'real_name' ],
            ];
            $Session->put( "projecter",$session_data );

            return redirect()->route( 'management.project.index' );

        }
        else{
            return redirect()->route( 'management.project.login' );
        }
    }


    public function index()
    {
        $Session   = Session();
        $projecter = $Session->get( 'projecter' );
        if (empty( $projecter["projecter_id"]  )){
            return redirect()->route( 'management.project.login' )->with( [ "meg" => "登陆过期，请重新登陆" ] );
        }
        $projecter[ 'not_begin' ] = $this->getNotBegin();
        $Session->put( "projecter",$projecter );
        if (empty( $projecter )){

            return redirect()->route( 'management.project.login' )->with( [ "meg" => "登陆过期，请重新登陆" ] );
        }
        $where_project = [
            "admin_id"    => $projecter[ 'projecter_id' ],
            "claim_state" => config( 'config.claim_state.project' ),
        ];

        $with_project = [
            "ProgressList",
            "Progress",
            "Product",
            "FirstType",
        ];
        $processNum   = getTaskNumber( $projecter[ 'projecter_id' ],$where_project );
        $ProcessModel = Progress::with( $with_project )->where( $where_project )->paginate( $this->pageNumber );
        if ($ProcessModel->isNotEmpty()){
            $data = [
                "project"    => $ProcessModel,
                "processNum" => $processNum,
            ];
        }
        else{
            $data = [
                "project"    => [],
                "processNum" => $processNum,
            ];
        }

        return view( 'departmentManagement/project/index',$data );

    }

//    public function indexSearch()
//    {
//        $Session   = Session();
//        $projecter = $Session->get( 'projecter' );
//        if (empty( $projecter )){
//            return redirect()->route( 'management.project.login' )->with( [ "meg" => "登陆过期，请重新登陆" ] );
//        }
//        $request = Request::all();
//        $keywords="";
//        if (isset($request['search'])) {
//            $keywords = $request['search'];
//        }
//        $projecter[ 'not_begin' ] = $this->getNotBegin();
//        $Session->put( "projecter",$projecter );
//        if (empty( $projecter )){
//
//            return redirect()->route( 'management.project.login' )->with( [ "meg" => "登陆过期，请重新登陆" ] );
//        }
//        $where_project = [
//            "admin_id"    => $projecter[ 'projecter_id' ],
//            "claim_state" => config( 'config.claim_state.project' ),
//        ];
//
//        $with_project = [
//            "ProgressList",
//            "Progress",
//            "Product",
//            "FirstType",
//        ];
//        $processNum   = getTaskNumber( $projecter[ 'projecter_id' ],$where_project );
//        $ProcessModel = Progress::with( $with_project )->where( $where_project )->paginate( $this->pageNumber );
//        if ($ProcessModel->isNotEmpty()){
//            $data = [
//                "project"    => $ProcessModel,
//                "processNum" => $processNum,
//                "keywords"=>$keywords
//            ];
//        }
//        else{
//            $data = [
//                "project"    => [],
//                "processNum" => $processNum,
//                "keywords"=>$keywords
//            ];
//        }
//
//        return view( 'departmentManagement/project/indexSearch',$data );
//
//    }

    public function projectCertainSearch()
    {
        $Session   = Session();
        $projecter = $Session->get( 'projecter' );
        if (empty( $projecter )){
            return redirect()->route( 'management.project.login' )->with( [ "meg" => "登陆过期，请重新登陆" ] );
        }
        $company=Request::input('company');
        $is_renew=Request::input('is_renew');
        $product_name=Request::input('product_name');
        $applicant=Request::input('applicant');
        $phone=Request::input('phone');
        $created_at=Request::input('created_at');
        $projecter[ 'not_begin' ] = $this->getNotBegin();
        $Session->put( "projecter",$projecter );
        if (empty( $projecter )){

            return redirect()->route( 'management.project.login' )->with( [ "meg" => "登陆过期，请重新登陆" ] );
        }
        $where_project = [
            "admin_id"    => $projecter[ 'projecter_id' ],
            "claim_state" => config( 'config.claim_state.project' ),
        ];

        $with_project = [
            "ProgressList",
            "Progress",
            "Product",
            "FirstType",
        ];
//        dd($company);
        $processNum   = getTaskNumber( $projecter[ 'projecter_id' ],$where_project );
        $ProcessModel = Progress::with( $with_project )
            ->join('product','product.id','=','progress.product_id')
            ->where( $where_project )
            ->when($company, function ($query) use ($company) {
                return $query->where('product.company', $company);
            })
            ->when($is_renew, function ($query) use ($is_renew) {
                return $query->where('progress.is_renew', $is_renew);
            })
            ->when($product_name, function ($query) use ($product_name) {
                return $query->where('product.name', $product_name);
            })
            ->when($applicant, function ($query) use ($applicant) {
                return $query->where('product.applicant', $applicant);
            })
            ->when($phone, function ($query) use ($phone) {
                return $query->where('product.phone', $phone);
            })
            ->when($created_at, function ($query) use ($created_at) {
                return $query->where('product.created_at','like','%'.$created_at.'%');
            })
            ->paginate( $this->pageNumber );
        if ($ProcessModel->isNotEmpty()){
            $data = [
                "project"    => $ProcessModel,
                "processNum" => $processNum,
            ];
        }
        else{
            $data = [
                "project"    => [],
                "processNum" => $processNum,
            ];
        }

        return view( 'departmentManagement/project/indexSearch',$data );
    }


    public function getNotBegin()
    {
        $where_progress = [
            "claim_state"    => config( 'config.claim_state.business' ),
            "business_state" => 5,
            "first_type_id"  => 4,
        ];
        $ProcessModel   = Progress::where( $where_progress )->get();
        $count          = 0;
        if (!empty( $ProcessModel )){
            $count = count( $ProcessModel->toArray() );
        }

        return $count;
    }


    public function userInfo()
    {


        $Session   = Session();
        $projecter = $Session->get( 'projecter' );
        if (empty( $projecter )){
            return redirect()->route( 'management.project.login' )->with( [ "meg" => "登陆过期，请重新登陆" ] );
        }

        $where_admin = [ "type" => 3,"id" => $projecter[ 'projecter_id' ],
        ];
        $Admin_Model = Admin::where( $where_admin )->first();
        if (!empty( $Admin_Model )){
            $admin = $Admin_Model->toArray();
        }
        $data = [ "admin" ];

        return view( 'departmentManagement/project/userInfo',compact( $data ) );

    }


    public function claimCenter()
    {

        $Session   = Session();
        $projecter = $Session->get( 'projecter' );
        if (empty( $projecter["projecter_id"] )){
            return redirect()->route( 'management.project.login' )->with( [ "meg" => "登陆过期，请重新登陆" ] );
        }
        $with_progress            = [
            "Product",
            "FirstType",
        ];
        $where_progress           = [
            "claim_state"    => config( 'config.claim_state.business' ),
            "business_state" => 5,
            "first_type_id"  => 4,
        ];
        $ProcessModel             = Progress::with( $with_progress )
            ->where( $where_progress )
            ->orderBy( "id" )
            ->orderBy( "is_cancel" )
            ->paginate( $this->pageNumber );
        $projecter[ 'not_begin' ] = $ProcessModel->total();
        $Session->put( "projecter",$projecter );
        if ($ProcessModel->isNotEmpty()){
            $data = [
                "process" => $ProcessModel,
            ];
        }
        else{
            $data = [
                "process" => [],
            ];
        }

        return view( 'departmentManagement/project/claimCenter',$data );

    }

    public function claimCenterSearch()
    {
        $Session   = Session();
        $projecter = $Session->get( 'projecter' );
        if (empty( $projecter["projecter_id"] )){
            return redirect()->route( 'management.project.login' )->with( [ "meg" => "登陆过期，请重新登陆" ] );
        }
        $request = Request::all();
        $keywords="";
        if (isset($request['search'])) {
            $keywords = $request['search'];
        }
        $with_progress            = [
            "Product",
            "FirstType",
        ];
        $where_progress           = [
            "claim_state"    => config( 'config.claim_state.business' ),
            "business_state" => 5,
            "first_type_id"  => 4,
        ];
        $ProcessModel             = Progress::with( $with_progress )
            ->where( $where_progress )
            ->orderBy( "id" )
            ->orderBy( "is_cancel" )
            ->paginate( 0);
        $projecter[ 'not_begin' ] = $ProcessModel->total();
        $Session->put( "projecter",$projecter );
        if ($ProcessModel->isNotEmpty()){
            $data = [
                "process" => $ProcessModel,
                "keywords"=>$keywords
            ];
        }
        else{
            $data = [
                "process" => [],
                "keywords"=>$keywords
            ];
        }

        return view( 'departmentManagement/project/claimCenter',$data );

    }

    /**
     * @return string  返回Json 数据。
     */

    public function toClaim()
    {


        $request = Request::all();
        DB::beginTransaction();
        try{
            $Session   = Session();
            $projecter = $Session->get( 'projecter' );
            $date      = date( "Y-m-d H:i:s",time() );
            $item      = Progress::find( $request[ 'project_id' ] );
            if (empty( $item )){
                throw new \Exception( "任务认领失败，该产品未找到，请重试",0001 );
            }
            $item[ 'claim_state' ] = config( 'config.claim_state.project' );
            $item[ 'admin_id' ]    = $projecter[ 'projecter_id' ];
            $item[ 'updated_at' ]  = $date;
            $item[ 'state' ]       = config( 'config.product_state_map.busy' );
            $item[ 'agent' ]       = $projecter[ 'projecter_name' ];
            $item_res              = $item->save();
            if (!$item_res){
                throw new \Exception( "任务认领失败，请重试",0002 );
            }
            $operation = [
                'product_id'    => $item[ 'product_id' ],
                'operator_id'   => $projecter[ 'projecter_id' ],
                'operator_type' => config( 'config.operation_role.admin' ),
                'content'       => '认领本次任务',
                "operator_name" => $projecter[ 'projecter_name' ],
            ];
            $ope_res   = addOperation( $operation );
            if (!$ope_res){
                throw new \Exception( "任务认领失败，请重试",0003 );
            }
            //            $productModel = Product::find( $item[ 'product_id' ] );
            //            if (empty( $productModel )){
            //                throw new \Exception( "任务认领失败3，该产品未找到，请重试" );
            //            }
            //            $productModel[ 'state' ] = config( 'config.product_state_map.busy' );
            //            $productModel[ 'agent' ] =  $projecter[ 'projecter_name' ];
            //            $product_res             = $productModel->save();
            //            if (!$product_res){
            //                throw new \Exception( "任务认领失败4，更新状态失败，请重试" );
            //            }
            DB::commit();
            WechatController::updateProgressNotice( $item[ 'product_id' ] );//微信通知进度

            return ;
        } catch (\Exception $exception){
            DB::rollback();

            if (empty( $exception->getCode() )){
                return Response::show( 1,"更新任务进度失败,未知错误请重试" );
            }
            else{
                return Response::show( 1,$exception->getMessage() . " 错误码：" . $exception->getCode() );
            }
        }
    }


    public function updateProgress()
    {


        $request = Request::all();
        DB::beginTransaction();
        try{
            $Session   = Session();
            $projecter = $Session->get( 'projecter' );
            $date      = date( "Y-m-d H:i:s",time() );
            $item      = Progress::find( $request[ 'process_id' ] );
            if (empty( $item )){
                throw new \Exception( "任务认领失败，该产品未找到，请重试",0001 );
            }
            $item[ 'progress_list_id' ] = $request[ 'process_list_id' ];
            $item[ 'updated_at' ]       = $date;
            $item[ 'claim_state' ]      = config( 'config.claim_state.project' );
            $item[ 'admin_id' ]         = $projecter[ 'projecter_id' ];
            $item[ 'updated_at' ]       = $date;
            $item[ 'is_push' ]          = $request[ 'is_push' ] == "true" ? 1:0;
            $item[ 'urge' ]             = $request[ 'is_end_money' ] == "true" ? 1:0;
            $item['agent']=$projecter[ 'projecter_name' ];
            $process_list                        = ProgressList::find( $request[ 'process_list_id' ] );
            $productModel                        = Product::find( $item[ 'product_id' ] );
            $productModel[ 'name' ]              = $request[ 'name' ];
            $productModel[ 'registration_area' ] = $request[ 'registration_area' ];
            $productModel[ 'registration_time' ] = $request[ 'registration_time' ];
            $productModel[ 'number' ]            = $request[ 'product_number' ];
            if(!empty( $request[ "authority_time" ])){
                $productModel[ 'authority_time' ]=  $request[ "authority_time" ];
            }
            if (in_array( $process_list[ 'progress_state' ],[ 1,2,3 ] )){
                if ($process_list[ 'progress_state' ] == 1){
                    $item[ 'state' ] = config( 'config.product_state_map.adopt' );
                }
                else{
                    $item[ 'state' ] = config( 'config.product_state_map.closed' );
                }

                $FirstType                        = FirstType::find( $item[ 'first_type_id' ] );
                $update_time                      = strtotime( $productModel[ 'authority_time' ] . " + " . $FirstType[ 'time' ] . "year" );
                $productModel[ 'authority_time' ] = date( "Y-m-d H:i:s",$update_time );

            }
            $product_res = $productModel->save();
            $item_res    = $item->save();
            if ((!$item_res) && (!$product_res)){
                throw new \Exception( "更新任务进度失败，请重试",0002 );
            }
            $operation = [
                'product_id'    => $item[ 'product_id' ],
                'process_id'    => (int)$request[ 'process_id' ],
                'progress_list_id'    =>(int) $request[ 'process_list_id' ],
                'operator_id'   => $projecter[ 'projecter_id' ],
                'operator_type' => config( 'config.operation_role.admin' ),
                'content'       => $request[ 'content' ],
                "operator_name" => $projecter[ 'projecter_name' ],
            ];
            $ope_res   = addOperation( $operation );
            if (!$ope_res){
                throw new \Exception( "更新任务进度失败，请重试",0003 );
            }

            DB::commit();
            if ($item[ 'is_push' ]){
                WechatController::updateProgressNotice( $item[ 'product_id' ] );//微信通知进度
                exit();
            }

            return Response::show( 0,"更新任务进度成功" );
        } catch (\Exception $exception){
            DB::rollback();

            if (empty( $exception->getCode() )){
                return Response::show( 1,"更新任务进度失败,未知错误请重试" );
            }
            else{
                return Response::show( 1,$exception->getMessage() . " 错误码：" . $exception->getCode() );
            }

        }


    }


    public function productDetail()
    {
        $Session   = Session();
        $request   = Request::all();
        $id        = $request[ 'product_id' ];
        $projecter = $Session->get( 'projecter' );
        if (empty( $projecter )){
            return redirect()->route( 'management.project.login' )->with( [ "meg" => "登陆过期，请重新登陆" ] );
        }
        $with_product  = [
            "ProgressState",
            "FirstType",
            "SecondType",
            "Files",
            "Progress"  => function ($query){
                $query->orderBy( "id" );
            },
            "Operation" => function ($query){
                $query->orderBy( "id","desc" );
            },
        ];
        $where_product = [
            "id" => $id,
        ];
        $productModel  = Product::with( $with_product )->where( $where_product )->first();
        if (!empty( $productModel )){
            $product = $productModel->toArray();
        }
        else{
            $product = [];
        }

        // dd(collect($productModel)->toArray());
        $returnData = [ 'product' ];

        return view( 'departmentManagement/project/commodityDetail',compact( $returnData ) );

    }


    public function deleteFile()
    {
        $request    = Request::all();
        $where_file = [
            "id" => $request[ 'file_id' ],
        ];
        $Session    = Session();
        $projecter  = $Session->get( 'projecter' );
        if (empty( $projecter )){
            return redirect()->route( 'management.project.login' )->with( [ "meg" => "登陆过期，请重新登陆" ] );
        }
        $fileModel   = Files::find( $request[ 'file_id' ] );
        $storage     = Storage::disk( "file" );
        $del_file    = $storage->delete( $fileModel[ 'url' ] );
        $delete_file = Files::where( $where_file )->delete();
        //TODO  删除OSS存储文件
        if ($delete_file){
            $content   = "删除了" . $request[ 'file_name' ] . "文件";
            $operation = [
                'product_id'    => $request[ 'productId' ],
                'operator_id'   => $projecter[ 'projecter_id' ],
                'operator_type' => config( 'config.operation_role.admin' ),
                'content'       => $content,
                "operator_name" => $projecter[ 'projecter_name' ],
            ];

            addOperation( $operation );

            return Response::show( 0,"删除文件成功",$operation );
        }
        else{
            return Response::show( 1,"删除文件失败" );
        }
    }


    public function changePassword()
    {


        $Session   = Session();
        $projecter = $Session->get( 'projecter' );

        return view( 'departmentManagement/project/changePassword' );

    }


    public function doChangePassword()
    {

        $request   = Request::all();
        $Session   = Session();
        $projecter = $Session->get( 'projecter' );
        if (empty( $projecter )){
            return redirect()->route( 'management.project.login' )->with( [ "meg" => "登陆过期，请重新登陆" ] );
        }
        $where_admin = [ "type" => 3,"id" => $projecter[ 'projecter_id' ],
        ];
        $Admin_Model = Admin::where( $where_admin )->first();
        if (!empty( $Admin_Model )){
            $admin = $Admin_Model->toArray();
            if ($admin[ 'password' ] == md5( $request[ 'old_pwd' ] )){
                if ($request[ 'require_pwd' ] == $request[ 'new_pwd' ]){
                    if ($request[ 'old_pwd' ] != $request[ 'new_pwd' ]){
                        $adminModel               = Admin::find( $projecter[ 'projecter_id' ] );
                        $adminModel[ 'password' ] = md5( $request[ 'new_pwd' ] );
                        if ($adminModel->save()){
                            return Response::show( 0,"修改成功" );
                        }
                        else{
                            return Response::show( 1,"修改失败" );
                        }
                    }
                    else{
                        return Response::show( 101,"修改失败，原密码与新密码一致" );
                    }
                }
                else{
                    return Response::show( 102,"修改失败，确认密码与新密码不一致" );
                }
            }
            else{
                return Response::show( 103,"修改失败，旧密码输入错误" );
            }

        }
        else{
            return Response::show( 4,"修改失败，信息错误" );
        }


    }


    public function uploadFile(Req $request)
    {
        $Session   = Session();
        $processer = $Session->get( 'processer' );
        if (empty( $processer )){
            return redirect()->route( 'management.project.login' )->with( [ "meg" => "登陆过期，请重新登陆" ] );
        }
        try{
            $file          = $request->file( 'file' );
            $fileName      = $request->filename;
            $filetype      = config( "config.file_path.OFFICAL" );
            $product_model = Product::find( $request->product_id );
            $path_name     = md5( $product_model[ 'user_id' ] ) . "/" . $filetype . "/" . md5( $request->product_id );
            $info          = uploadFile( $file,$path_name,$fileName );
            if ($info){
                $time     = date( "Y-m-d H:i:s",time() );
                $stroage  = Storage::disk( 'file' );
                $saveData = [
                    "product_id" => $request->product_id,
                    "name"       => $fileName,
                    //                    "url"        => $stroage->url($info[ 'url' ]),
                    "url"        => $info[ 'url' ],
                    "created_at" => $time,
                    "updated_at" => $time,
                ];
                $res      = DB::table( 'files' )->updateOrInsert( $saveData );
                if ($res){
                    return Response::show( 0,"文件上传成功" );
                }
                else{
                    return Response::show( 2,"文件保存失败" );
                }
            }
            else{
                return Response::show( 2,"文件上传失败" );
            }
        } catch (Exception $exception){
            return Response::show( 3,"文件上传失败,未知错误" );
        }
    }


    /**
     * 下载文件
     */

    public function doloadFile()
    {
        $request   = Request::all();
        $fileModel = Files::find( $request[ 'file_id' ] );
        if ($fileModel){
            $storage = Storage::disk( "file" );
            $path    = $storage->url( $fileModel[ 'url' ] );
            try{
                download( $path,$fileModel[ 'name' ] );
            } catch (\Exception $exception){
                return error_return( "未找到文件" );
            }
        }
        else{
            return error_return( "未找到文件信息" );
        }
    }


    /**
     * 下载官方文件
     */

    public function downloadFile()
    {
        $request = Request::all();
        $Product = Product::find( $request[ 'product_id' ] );
        if ($Product){
            $storage = Storage::disk( "file" );
            $path    = $storage->url( $Product[ 'file' ] );
            try{
                download( $path,"报件资料" );
            } catch (\Exception $exception){
                return error_return( "未找到文件" );
            }
        }
        else{
            return error_return( "未找到文件信息" );
        }
    }


}
